% visualize_buffer_lifetimes.m
% 绘制每个Buffer的生命周期图。
% *** 已修改: 增加输出路径参数并自动保存图表 ***
function visualize_buffer_lifetimes(history, type_code_to_plot, output_dir, file_prefix)
    if ~exist(output_dir, 'dir'), mkdir(output_dir); end
    fig_path_png = fullfile(output_dir, [file_prefix, '_buffer_lifetimes.png']);
    fig_path_fig = fullfile(output_dir, [file_prefix, '_buffer_lifetimes.fig']);
    fig = figure('Name', sprintf('Buffer 生命周期 (Cache Type %d)', type_code_to_plot), 'Visible', 'off');
    hold on;
    
    buf_ids = keys(history.buffer_lifetimes);
    min_duration_steps = 5;
    top_k_buffers = 200;
    
    durations = zeros(1, numel(buf_ids));
    for i = 1:numel(buf_ids)
        bid = buf_ids{i};
        intervals = history.buffer_lifetimes(bid);
        dsum = 0;
        for j = 1:length(intervals)
            if intervals{j}{3} == type_code_to_plot
                dsum = dsum + (intervals{j}{2} - intervals{j}{1});
            end
        end
        durations(i) = dsum;
    end
    
    valid_idx = find(durations >= min_duration_steps);
    buf_ids = buf_ids(valid_idx);
    durations = durations(valid_idx);
    
    if numel(buf_ids) > top_k_buffers
        [~, order] = sort(durations, 'descend');
        order = order(1:top_k_buffers);
        buf_ids = buf_ids(order);
    end
    
    y_pos = 1;
    y_labels = {};
    
    for i = 1:length(buf_ids)
        buf_id = buf_ids{i};
        intervals = history.buffer_lifetimes(buf_id);
        
        is_in_type = false;
        for j = 1:length(intervals)
            if intervals{j}{3} == type_code_to_plot
                is_in_type = true;
                break;
            end
        end
        
        if is_in_type
            y_labels{end+1} = num2str(buf_id);
            for j = 1:length(intervals)
                interval = intervals{j};
                if interval{3} == type_code_to_plot
                    start_step = interval{1};
                    end_step = interval{2};
                    patch([start_step, end_step, end_step, start_step], ...
                          [y_pos-0.4, y_pos-0.4, y_pos+0.4, y_pos+0.4], ...
                           'b', 'EdgeColor', 'k');
                end
            end
            y_pos = y_pos + 1;
        end
    end
    
    hold off;
    
    if ~isempty(y_labels)
        yticks(1:(y_pos-1));
        yticklabels(y_labels);
    end
    ylim([0, y_pos]);
    xlim([0, length(history.steps)]);
    title(sprintf('Buffer 生命周期 (Cache Type %d)', type_code_to_plot));
    xlabel('调度步骤 (Step)');
    ylabel('Buffer ID');
    grid on;
    set(gca, 'YDir','reverse');
    saveas(fig, fig_path_png);
    saveas(fig, fig_path_fig);
    close(fig);
end